package com.fubowen.lepton.ui.reader.recycler

import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.ViewPropertyAnimator
import android.widget.OverScroller

class SliderHelper(private val view: View) {
    private var startX = 0f
    private var startY = 0f
    private var translationY = 0f
    private val context: Context = view.context
    private var animator: ViewPropertyAnimator? = null
    private val scroller = OverScroller(context)
    private val gestureDetector = GestureDetector(context, gestureListener())
    private var isHidden = true
    var onCloseAction: () -> Unit = {}

    fun setTranslationY() {
        if (scroller.computeScrollOffset()) {
            val y = scroller.currY
            val dy = y - translationY
            view.translationY += dy
            translationY = y.toFloat()
        }
    }

    private fun gestureListener() = object : GestureDetector.SimpleOnGestureListener() {
        override fun onFling(
            e1: MotionEvent?,
            e2: MotionEvent,
            velocityX: Float,
            velocityY: Float
        ): Boolean {
            scroller.fling(0, translationY.toInt(), 0, velocityY.toInt(), 0, 0, 0, view.height)
            return true
        }
    }

    init {
        view.setOnTouchListener { view, event ->
            gestureDetector.onTouchEvent(event)
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    animator?.cancel()
                    startX = event.rawX
                    startY = event.rawY
                }

                MotionEvent.ACTION_MOVE -> {
                    val dx = event.rawX - startX
                    val dy = event.rawY - startY
                    translationY = view.translationY + dy
                    if (translationY < 0) {
                        translationY = 0f
                    } else if (translationY > view.height) {
                        translationY = view.height.toFloat()
                    }
                    view.translationY = translationY
                    startX = event.rawX
                    startY = event.rawY
                }

                MotionEvent.ACTION_UP -> {
                    animator = view.animate().setDuration(200)
                    if (translationY > view.height / 2) {
                        animator?.translationY(view.height.toFloat())
                        animator?.withEndAction {
                            onCloseAction()
                            view.postDelayed({ view.translationY = 0f }, 250)
                        }
                    } else {
                        animator?.translationY(0f)
                    }
                    animator?.start()
                }
            }
            true
        }
    }
}